/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import pojos.Bill;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.PreexistingEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pojos.Exporter;
import pojos.Customer;
import pojos.BillItem;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author A7med Kotb
 */
public class BillJpaController implements Serializable {

    public BillJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Bill bill) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (bill.getBillItemCollection() == null) {
            bill.setBillItemCollection(new ArrayList<BillItem>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Exporter exporterID = bill.getExporterID();
            if (exporterID != null) {
                exporterID = em.getReference(exporterID.getClass(), exporterID.getIdExporter());
                bill.setExporterID(exporterID);
            }
            Customer customerID = bill.getCustomerID();
            if (customerID != null) {
                customerID = em.getReference(customerID.getClass(), customerID.getIdCustomer());
                bill.setCustomerID(customerID);
            }
            Collection<BillItem> attachedBillItemCollection = new ArrayList<BillItem>();
            for (BillItem billItemCollectionBillItemToAttach : bill.getBillItemCollection()) {
                billItemCollectionBillItemToAttach = em.getReference(billItemCollectionBillItemToAttach.getClass(), billItemCollectionBillItemToAttach.getIdBillItem());
                attachedBillItemCollection.add(billItemCollectionBillItemToAttach);
            }
            bill.setBillItemCollection(attachedBillItemCollection);
            em.persist(bill);
            if (exporterID != null) {
                exporterID.getBillCollection().add(bill);
                exporterID = em.merge(exporterID);
            }
            if (customerID != null) {
                customerID.getBillCollection().add(bill);
                customerID = em.merge(customerID);
            }
            for (BillItem billItemCollectionBillItem : bill.getBillItemCollection()) {
                Bill oldBillIDOfBillItemCollectionBillItem = billItemCollectionBillItem.getBillID();
                billItemCollectionBillItem.setBillID(bill);
                billItemCollectionBillItem = em.merge(billItemCollectionBillItem);
                if (oldBillIDOfBillItemCollectionBillItem != null) {
                    oldBillIDOfBillItemCollectionBillItem.getBillItemCollection().remove(billItemCollectionBillItem);
                    oldBillIDOfBillItemCollectionBillItem = em.merge(oldBillIDOfBillItemCollectionBillItem);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findBill(bill.getIdBill()) != null) {
                throw new PreexistingEntityException("Bill " + bill + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Bill bill) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Bill persistentBill = em.find(Bill.class, bill.getIdBill());
            Exporter exporterIDOld = persistentBill.getExporterID();
            Exporter exporterIDNew = bill.getExporterID();
            Customer customerIDOld = persistentBill.getCustomerID();
            Customer customerIDNew = bill.getCustomerID();
            Collection<BillItem> billItemCollectionOld = persistentBill.getBillItemCollection();
            Collection<BillItem> billItemCollectionNew = bill.getBillItemCollection();
            if (exporterIDNew != null) {
                exporterIDNew = em.getReference(exporterIDNew.getClass(), exporterIDNew.getIdExporter());
                bill.setExporterID(exporterIDNew);
            }
            if (customerIDNew != null) {
                customerIDNew = em.getReference(customerIDNew.getClass(), customerIDNew.getIdCustomer());
                bill.setCustomerID(customerIDNew);
            }
            Collection<BillItem> attachedBillItemCollectionNew = new ArrayList<BillItem>();
            for (BillItem billItemCollectionNewBillItemToAttach : billItemCollectionNew) {
                billItemCollectionNewBillItemToAttach = em.getReference(billItemCollectionNewBillItemToAttach.getClass(), billItemCollectionNewBillItemToAttach.getIdBillItem());
                attachedBillItemCollectionNew.add(billItemCollectionNewBillItemToAttach);
            }
            billItemCollectionNew = attachedBillItemCollectionNew;
            bill.setBillItemCollection(billItemCollectionNew);
            bill = em.merge(bill);
            if (exporterIDOld != null && !exporterIDOld.equals(exporterIDNew)) {
                exporterIDOld.getBillCollection().remove(bill);
                exporterIDOld = em.merge(exporterIDOld);
            }
            if (exporterIDNew != null && !exporterIDNew.equals(exporterIDOld)) {
                exporterIDNew.getBillCollection().add(bill);
                exporterIDNew = em.merge(exporterIDNew);
            }
            if (customerIDOld != null && !customerIDOld.equals(customerIDNew)) {
                customerIDOld.getBillCollection().remove(bill);
                customerIDOld = em.merge(customerIDOld);
            }
            if (customerIDNew != null && !customerIDNew.equals(customerIDOld)) {
                customerIDNew.getBillCollection().add(bill);
                customerIDNew = em.merge(customerIDNew);
            }
            for (BillItem billItemCollectionOldBillItem : billItemCollectionOld) {
                if (!billItemCollectionNew.contains(billItemCollectionOldBillItem)) {
                    billItemCollectionOldBillItem.setBillID(null);
                    billItemCollectionOldBillItem = em.merge(billItemCollectionOldBillItem);
                }
            }
            for (BillItem billItemCollectionNewBillItem : billItemCollectionNew) {
                if (!billItemCollectionOld.contains(billItemCollectionNewBillItem)) {
                    Bill oldBillIDOfBillItemCollectionNewBillItem = billItemCollectionNewBillItem.getBillID();
                    billItemCollectionNewBillItem.setBillID(bill);
                    billItemCollectionNewBillItem = em.merge(billItemCollectionNewBillItem);
                    if (oldBillIDOfBillItemCollectionNewBillItem != null && !oldBillIDOfBillItemCollectionNewBillItem.equals(bill)) {
                        oldBillIDOfBillItemCollectionNewBillItem.getBillItemCollection().remove(billItemCollectionNewBillItem);
                        oldBillIDOfBillItemCollectionNewBillItem = em.merge(oldBillIDOfBillItemCollectionNewBillItem);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = bill.getIdBill();
                if (findBill(id) == null) {
                    throw new NonexistentEntityException("The bill with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Bill bill;
            try {
                bill = em.getReference(Bill.class, id);
                bill.getIdBill();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The bill with id " + id + " no longer exists.", enfe);
            }
            Exporter exporterID = bill.getExporterID();
            if (exporterID != null) {
                exporterID.getBillCollection().remove(bill);
                exporterID = em.merge(exporterID);
            }
            Customer customerID = bill.getCustomerID();
            if (customerID != null) {
                customerID.getBillCollection().remove(bill);
                customerID = em.merge(customerID);
            }
            Collection<BillItem> billItemCollection = bill.getBillItemCollection();
            for (BillItem billItemCollectionBillItem : billItemCollection) {
                billItemCollectionBillItem.setBillID(null);
                billItemCollectionBillItem = em.merge(billItemCollectionBillItem);
            }
            em.remove(bill);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Bill> findBillEntities() {
        return findBillEntities(true, -1, -1);
    }

    public List<Bill> findBillEntities(int maxResults, int firstResult) {
        return findBillEntities(false, maxResults, firstResult);
    }

    private List<Bill> findBillEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Bill.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Bill findBill(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Bill.class, id);
        } finally {
            em.close();
        }
    }

    public int getBillCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Bill> rt = cq.from(Bill.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
